package gu.sql2java.observer;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;

import com.google.common.base.Strings;
import gu.simplemq.SimpleLog;

/**
 * JDBC工具类
 * @author guyadong
 *
 */
public class JDBCUtility extends gu.sql2java.utils.JDBCUtility {
	/**
	 * 检查数据库类型及版本是否满足要求,不满足则抛出异常
	 * @param metaData
	 * @param requiredProductName 要求的数据库名,such as 'MySQL'
	 * @param requiredMinVersion     要求的数据最低版本号,such as '5.7.36'
	 * @param requiredMaxVersion    要求的数据最高版本号,为{@code null}或空忽略
	 * @throws SQLException  从DatabaseMetaData读取数据异常
	 */
	public static void checkDatatbaseVersion(DatabaseMetaData metaData,String requiredProductName,String requiredMinVersion,String requiredMaxVersion) throws SQLException{
		String productName = checkNotNull(metaData,"metaData is null").getDatabaseProductName();
		DefaultArtifactVersion minVersion = new DefaultArtifactVersion(checkNotNull(requiredMinVersion,"requiredMinVersion is null"));
		DefaultArtifactVersion version = new DefaultArtifactVersion(metaData.getDatabaseProductVersion());
		SimpleLog.log("database {} {}",productName,version);
		checkState(productName.equals(requiredProductName),"%s required",requiredMinVersion);
		checkState(version.compareTo(minVersion) >= 0,"Sorry, %s min version %s is required",requiredProductName,minVersion);
		if(!Strings.isNullOrEmpty(requiredMaxVersion)){
			DefaultArtifactVersion maxVersion = new DefaultArtifactVersion(requiredMaxVersion);
			checkState(version.compareTo(maxVersion) <= 0,"Sorry, %s max version %s is required",requiredProductName,maxVersion);
		}
	}
}
